import { 
  WebSocketGateway, 
  SubscribeMessage, 
  MessageBody, 
  ConnectedSocket,
  OnGatewayInit,
  OnGatewayConnection,
  OnGatewayDisconnect,
  WebSocketServer
} from '@nestjs/websockets';
import { Socket, Server } from 'socket.io';
import { ChatService } from './chat.service';
import { CreateChatDto } from './dto/create-chat.dto';
import { UpdateChatDto } from './dto/update-chat.dto';

@WebSocketGateway(4000, { 
  cors: { origin: '*' },
  transports: ['websocket'], //可选polling（HTTP长连接轮询）
})
export class ChatGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
  @WebSocketServer() server: Server;
  private clients: Array<string> = []
  constructor(private readonly chatService: ChatService) {}
  afterInit(server: Server) {
    console.log('afterInit')
  }
  handleConnection(client: Socket, ...args: any[]) {
    const { room } = client.handshake.query as any
    client.join(room)
    this.server.emit('in', client.id + '加入群聊');
    this.server.to(room).emit("inroom",client.id + ' 进入房间' + room);
    client.to(room).emit("inroom",' 我自己进入房间' + room);
  }

  handleDisconnect(client: Socket) {
    console.log(client.id + ' is handleDisconnect')
  }
  @SubscribeMessage('catRoom')
  catRoom(@MessageBody() body, @ConnectedSocket() client: Socket){
    const adapter = this.server.of("/").adapter
    const r = adapter.rooms.get('room1')
    if(r){
      client.send([...r])
    }
    
  }

  @SubscribeMessage('createChat')
  create(@MessageBody() createChatDto: CreateChatDto, @ConnectedSocket() client: Socket) {
    const result =  this.chatService.create(createChatDto);
    console.log(client.id + 'is createChat')
    client.emit('createChat', createChatDto)
  }

  @SubscribeMessage('findAllChat')
  findAll() {
    return this.chatService.findAll();
  }

  @SubscribeMessage('findOneChat')
  findOne(@MessageBody() id: number) {
    return this.chatService.findOne(id);
  }

  @SubscribeMessage('updateChat')
  update(@MessageBody() updateChatDto: UpdateChatDto) {
    return this.chatService.update(updateChatDto.id, updateChatDto);
  }

  @SubscribeMessage('removeChat')
  remove(@MessageBody() id: number) {
    return this.chatService.remove(id);
  }
}
